import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import FamilyTreeView from '../views/FamilyTreeView.vue' // 假设你有这个组件
import LoginView from '../views/LoginView.vue'
const UserManagementView = () => import('../views/UserManagementView.vue')

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/family-tree',
    name: 'family-tree',
    component: FamilyTreeView // 添加家族族谱组件路由
  },
  {
    path: '/about',
    name: 'about',
    // 懒加载组件
    component: () => import('../views/AboutView.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: LoginView
  },
  {
    path: '/user-management',
    name: 'user-management',
    component: UserManagementView
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

import { useAuthStore } from '../stores/auth'

// 路由守卫：未登录跳转到登录页
router.beforeEach((to, from, next) => {
  const auth = useAuthStore()
  if (to.name !== 'login' && !auth.isLoggedIn) {
    next({ name: 'login' })
  } else if (to.name === 'login' && auth.isLoggedIn) {
    next({ name: 'home' })
  } else {
    next()
  }
})

export default router